package cn.gowss.vnc.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.gowss.vnc.NovncProxyApplication;
import cn.gowss.vnc.utils.PropertiesUtils;

import java.nio.charset.StandardCharsets;

@Controller
public class IndexController {

	@RequestMapping("/")
	public String vnc(HttpServletRequest request, Model model) {
		String serverName = request.getHeader("Host").split(":")[0];
		String container = request.getParameter("container");
		String vncserver = container.split(":")[0];
		String vncport = container.split(":")[1];
		if(StringUtils.isEmpty(vncport)) {
			vncport = "5901";
		}
		String token = request.getParameter("token");
		String password = new String(Base64Utils.decodeFromString(token), StandardCharsets.UTF_8);
		if(StringUtils.isEmpty(password)) {
			password = "123456";
		}
		model.addAttribute("vncserver", vncserver);
		model.addAttribute("vncport", vncport);
		model.addAttribute("port", NovncProxyApplication.PROXY_PORT);
		model.addAttribute("password", password);
		model.addAttribute("serverName", serverName);
        return "index";
	}

	@RequestMapping("/viewOnly")
	public String viewOnly(HttpServletRequest request,Model model) {
		String serverName = request.getHeader("Host").split(":")[0];
		String container = request.getParameter("container");
		String vncserver = container.split(":")[0];
		String vncport = container.split(":")[1];
		if(StringUtils.isEmpty(vncport)) {
			vncport = "5901";
		}
		String token = request.getParameter("token");
		String password = new String(Base64Utils.decodeFromString(token), StandardCharsets.UTF_8);
		if(StringUtils.isEmpty(password)) {
			password = "123456";
		}
		model.addAttribute("vncserver", vncserver);
		model.addAttribute("vncport", vncport);
		model.addAttribute("port", NovncProxyApplication.PROXY_PORT);
		model.addAttribute("password", password);
		model.addAttribute("serverName", serverName);
		return "viewOnly";
	}

}
